import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: wangxin
 * Date: 2024-12-23
 * Time: 17:19
 */
public class MyUnionFindSet {
    public int[] elem;
    public MyUnionFindSet(int capacity){
        this.elem = new int[capacity];
        Arrays.fill(elem,-1);
    }
    public int findRoot(int val){
       if(val < 0){
           throw new IndexOutOfBoundsException("数据不合法，值为负数");
       }
        while(elem[val] >= 0){
            val = elem[val];
        }
        return val;
    }
    public boolean isUnionFindSet(int x1,int x2){
        int f1 = findRoot(x1);
        int f2 = findRoot(x2);
        if(f1 == f2){
            return true;
        }else{
            return false;
        }
    }
    public void union(int x1,int x2){
        int f1 = findRoot(x1);
        int f2 = findRoot(x2);
      if(f1 == f2){
          return;
      }
        elem[f1] = elem[f1]+elem[f2];
        elem[f2] = f1;
    }
    public int getCount(){
        int count = 0;
        for (int x:elem) {
            if(x < 0){
                count++;
            }
        }
        return count;
    }
 public void print(){
        for(int i = 0; i < elem.length;i++){
            System.out.print(elem[i]+" ");
        }
 }
    public static void main(String[] args) {
        MyUnionFindSet ufs = new MyUnionFindSet(10);
        ufs.union(0,6);
        ufs.union(0,7);
        ufs.union(0,8);
        ufs.union(1,4);
        ufs.union(1,9);
        ufs.union(2,3);
        ufs.union(2,5);
        ufs.print();
        System.out.println();
        System.out.println(ufs.getCount());
        System.out.println(ufs.isUnionFindSet(0,6));
        System.out.println(ufs.isUnionFindSet(1,6));
        ufs.union(0,1);
        System.out.println(ufs.getCount());
        ufs.print();
    }
}
